import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../../../domain/providers/upload_queue_provider.dart';

/// 上传文件的悬浮按钮组件
class UploadFab extends StatelessWidget {
  /// 上传完成后的回调函数，参数为上传任务数量
  final Function(int taskCount) onUploadComplete;

  /// 按钮上移的距离，默认为16
  final double marginBottom;

  /// 按钮左移的距离，默认为0
  final double marginRight;

  const UploadFab({
    Key? key,
    required this.onUploadComplete,
    this.marginBottom = 16,
    this.marginRight = 0,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      // 使用边距调整按钮位置 - 同时控制底部和右侧边距
      padding: EdgeInsets.only(bottom: marginBottom, right: marginRight),
      child: FloatingActionButton(
        onPressed: () => _uploadFiles(context),
        tooltip: '上传文件',
        elevation: 4.0, // 添加阴影效果
        child: const Icon(Icons.add),
      ),
    );
  }

  /// 上传文件方法
  Future<void> _uploadFiles(BuildContext context) async {
    try {
      // 获取上传队列
      final uploadQueueProvider = Provider.of<UploadQueueProvider>(
        context,
        listen: false,
      );

      // 从上传队列获取上传任务工厂
      final uploadTaskFactory = uploadQueueProvider.uploadTaskFactory;

      // 创建上传任务
      final tasks = await uploadTaskFactory.createUploadTasksFromPicker(
        directoryId: 0, // 上传到根目录
      );

      if (tasks.isNotEmpty) {
        // 添加任务到队列
        await uploadQueueProvider.addTasks(tasks);

        // 显示成功消息
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('已添加${tasks.length}个文件到上传队列'),
            duration: const Duration(seconds: 2),
          ),
        );

        // 调用上传完成回调函数
        onUploadComplete(tasks.length);
      }
    } catch (e) {
      // 显示错误消息
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('选择文件失败: ${e.toString()}')));
    }
  }
}
